package tcom.huitone.smspfm.dao.redis;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.Test;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.bin.common.utils.ArrayUtils;
import com.bin.common.utils.DateTimeUtils;
import com.huitone.smspfm.context.utils.ContextUtils;
import com.huitone.smspfm.core.config.AppStaticConfigs;
import com.huitone.smspfm.redis.impl.HashOpts;
import com.huitone.smspfm.redis.impl.KeyOpts;
import com.huitone.smspfm.redis.impl.ListOpts;
import com.huitone.smspfm.redis.impl.ScriptOpts;
import com.huitone.smspfm.redis.impl.SetOpts;
import com.huitone.smspfm.redis.impl.ZsetOpts;
import com.huitone.smspfm.redis.model.SmsEntity;
import com.huitone.smspfm.redis.pipeline.PipelineOpts;
import com.huitone.smspfm.redis.pipeline.PipelineOpts.ABExcuteCommands;
import com.huitone.smspfm.redis.pipeline.PipelineOpts.ExcuteCommands;

public class ReadData {
	
	String lua ="local key = KEYS[1] \n" +
				"local count = ARGV[1] \n" +
				"local array = {} \n" +
				"for i=0, count, 1 do \n" +
				    "local lvalue = redis.call(\"rpop\", key) \n" +
				    "local hvalue = redis.call(\"hmget\", \"SMInfo:\" .. lvalue, \"Srv_node\", \"ServiceCode\", \"SmType\", \"User\", \"Smcont\", \"Reportflag\", \"recvTime\", \"RecvModuleName\", \"DealModuleName\", \"SDealTime\", \"EdealTime\", \"DealResult\", \"DealResultDesc\", \"ConSm\", \"Send_seq\", \"Split_times\", \"SendTime\", \"SendResult\", \"SendResultDesc\", \"SendModuleName\", \"Notify_send_time\", \"RecvStatus\", \"RecvTime\", \"RecvErrorCode\", \"RecvErrorMsg\", \"ReportTime\", \"ReportModuleName\", \"CurDealDesc\", \"CurDealTime\", \"CurDealStatus\", \"SendPort\", \"OrgSrvNode\", \"OrgSerialNo\", \"SerialSegment\", \"GateLinkId\") \n" +
				    "table.insert(hvalue, lvalue) \n" +
				    "array[i] = hvalue \n" +
				"end \n" +
				"return array \n";
	
	private String lua2 = "function string.split(str, delimiter) \n" +
			"if str==nil or str=='' or delimiter==nil then \n" +
			"return nil \n" +
		"end \n" +
		
	    "local result = {} \n" +
	    "for match in (str..delimiter):gmatch(\"(.-)\"..delimiter) do \n" +
	        "table.insert(result, match) \n" +
	    "end \n" +
	    "return result \n" +
	"end \n" +

	"local level = ARGV[1] \n" +

	"local linkidsStr = ARGV[2] \n" +

	"local linkidsLst = string.split(linkidsStr, \",\") \n" +

	"local prilist = nil \n" +

	"local presize = 0 \n" +
	
	"if (linkidsLst ~= nil) then \n" +

	"if (level == \"0\") then \n" +
	    "for i,v in ipairs(linkidsLst) do \n" +
	        "local tmpprilist = \"SM:\"..v..\":Pri:0:List\" \n" +
	        "local size = redis.call(\"llen\", tmpprilist) \n" +
	        "if (prilist == nil) then \n" +
	            "prilist = tmpprilist \n" +
	            "presize = size \n" +
	        "else \n" +        
	           "if (size < presize) then \n" +
	              "prilist = tmpprilist \n" +
	               "presize = size\n" +
	           "end \n" +
	        "end \n" +
	    "end \n" +
	"else \n" +
	    "local alllevel = redis.call(\"zrangebyscore\", \"ConfigAllPLvZSet\", 0, 99999999999999) \n" +
	    "local preallsize = 0 \n" +
	    "local prelinkid = nil \n" +
	    "for i,v in ipairs(linkidsLst) do \n" +
	        "local tmpsize = 0 \n" +
	        "for j,k in ipairs(alllevel) do \n" +
	            "local tmpprilist = \"SM:\"..v..\":Pri:\"..k..\":List\" \n" +
	            "tmpsize = tmpsize + redis.call(\"llen\", tmpprilist) \n" +
	        "end \n" +
	        "if (prelinkid == nil) then \n" +
	            "prelinkid = v \n" +
	            "preallsize = tmpsize \n" +
	        "else \n" +
	            "if (tmpsize < preallsize) then \n" +
	                "prelinkid = v \n" +
	                "preallsize = tmpsize \n" +
	            "end \n" +
	        "end \n" +
	    "end \n" +
	    "if (prelinkid ~= nil) then \n" +
	    	"if (level ~= \"\") then \n" +
        		"prilist = \"SM:\"..prelinkid..\":Pri:\"..level..\":List\" \n" +
			"else \n" +
			    "local minlevel = redis.call(\"get\", \"ConfigMinPLvString\") \n" +
				"prilist = \"SM:\"..prelinkid..\":Pri:\"..minlevel..\":List\" \n" +
			"end \n" +
	    "end \n" +
	"end \n" +
	"end \n" +
	"return 0 \n";
	
	@Test
	public void readSbtSet() {
		
		/*ScriptOpts scriptOpts = ContextUtils.getInstance().getBean(ScriptOpts.class);
		
		long start1 = System.currentTimeMillis();
		
		DefaultRedisScript<List> script = new DefaultRedisScript<>(lua, List.class);
		
		List<Object> args = new ArrayList<>();
		args.add("10");
		args.addAll(SmsEntity.getColumns());
		
		List<List<String>> list = scriptOpts.getSMCacheAndHash(script, Collections.singletonList("SMCache"), "10");
		
		for (int i = 0 ; i < list.size() ; i ++) {
			System.out.println(list.get(i));
		}
		
		long end1 = System.currentTimeMillis();
		
		System.out.println(end1 - start1);*/
		
		ScriptOpts scriptOpts = ContextUtils.getInstance().getBean(ScriptOpts.class);
		
		DefaultRedisScript<List> script = new DefaultRedisScript<>(lua2, List.class);
		
		List<Object> args = new ArrayList<>();
		args.add("10");
		args.addAll(SmsEntity.getColumns());
		
		List<List<String>> list = scriptOpts.getSMCacheAndHash(script, Collections.singletonList("SMCache"), "10");
		
		for (int i = 0 ; i < list.size() ; i ++) {
			System.out.println(list.get(i));
		}
	}
	
	/**
	 * 查看应用登记集合
	 */
	@Test
	public void readSMModRegSet() {
		SetOpts setOpts = ContextUtils.getInstance().getBean(SetOpts.class);
		
		Cursor<Object> cursor = setOpts.scan("SMModRegSet", ScanOptions.scanOptions().build());
		
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	}
	
	/**
	 * 应用登记集合是否包含
	 */@Test
	public void isMemberSMModRegSet() {
		SetOpts setOpts = ContextUtils.getInstance().getBean(SetOpts.class);
		System.out.println(setOpts.isMember("SMModRegSet", "SMModInfo:kehuduan1"));
		
		HashOpts hashOpts = ContextUtils.getInstance().getBean(HashOpts.class);
		
		Map<String, Object> params = new HashMap<>();
		params.put("Status", "Stop");
		params.put("StopTime", DateTimeUtils.dateToStr(new Date(), "yyyyMMddHHmmss"));
		hashOpts.put("SMModInfo:kehuduan1", params);
		
		
	}
	
	@Test
	public void readSMInfo() {
		//HashOpts hashTest = ContextUtils.getInstance().getBean(HashOpts.class);
		
		//String string = hashTest.get("SMInfo:beb8adf13ce44280a9f9cbf843da4d2c:13560027888", "User");
		
		//System.out.println(string);
		
		//System.out.println("readSMInfo运行结束");
		
		System.out.println(SmsEntity.getColumns());
	}
	
	/**
	 * 缓存队列
	 */
	@Test
	public void readSMCache() {
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMCache", 0, listOpts.length("SMCache"));
		
		System.out.println("缓存队列！");
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}

	/**
	 * 禁止队列
	 */
	@Test
	public void readSMForbidList() {
		
		ZsetOpts zsetOpts = ContextUtils.getInstance().getBean(ZsetOpts.class);
		
		Set<String> strs = zsetOpts.rangeByScore("SMForbidZSet", 20, 20);
		
		for (String str:strs) {
			System.out.println(str);
		}
		
	}
	
	/**
	 * 重复队列
	 */
	@Test
	public void readSMRepList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMRepList", 0, listOpts.length("SMRepList"));
		
		System.out.println(list.size());
		for (String lt:list) {
			System.out.println(lt);
		}
		
	}
	
	/**
	 * 通知队列
	 */
	@Test
	public void readSMNotifyList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMNotifyList", 0, listOpts.length("SMNotifyList"));
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}
	
	/**
	 * 临时队列
	 */
	@Test
	public void readSMTempSet() {
		
		SetOpts setOpts = ContextUtils.getInstance().getBean(SetOpts.class);
		
		Cursor<Object> cursor = setOpts.scan("SMTempSet", ScanOptions.scanOptions().build());
		
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
		
	}
	
	/**
	 * 敏感词过滤队列
	 */
	@Test
	public void readSMSensList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMSensList", 0, listOpts.length("SMSensList"));
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}
	
	/**
	 * 黑名单过滤队列
	 */
	@Test
	public void readSMBlackList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMBlackList", 0, listOpts.length("SMBlackList"));
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}
	
	/**
	 * 无效用户过滤队列
	 */
	public void readSMInvalidList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMInvalidList", 0, listOpts.length("SMInvalidList"));
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}
	
	/**
	 * 优先级队列 
	 * 注意：修改gateId/pri 查询响应优先级列表
	 */
	public void readPriList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		String gateId = "";
		String pri = "";
		
		List<String> list = listOpts.range("SM:"+gateId+":Pri:"+pri+":List", 0, listOpts.length("SM:"+gateId+":Pri:"+pri+":List"));
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}
	
	/**
	 * 匹配出目的地的上行短信队列
	 */
	@Test
	public void readSMMoDealList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMMoDealList", 0, listOpts.length("SMMoDealList"));
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}
	
	/**
	 * 未匹配出目的地的上行短信队列
	 */
	@Test
	public void readSMMoEndList() {
		
		ListOpts listOpts = ContextUtils.getInstance().getBean(ListOpts.class);
		
		List<String> list = listOpts.range("SMMoEndList", 0, listOpts.length("SMMoEndList"));
		
		for (String lt:list) {
			System.out.println(lt);
		}
	}
}
